package org.example.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Http 工具
 *
 * @author jw.z
 */
public final class HttpTool {

    private static final Logger log = LoggerFactory.getLogger(HttpTool.class);


    private HttpTool() {
    }


    // 不包含文件的接口使用application/x-www-form-urlencoded请求头请求
    public static String post(String httpUrl) {
        return post(httpUrl, null, null);
    }


    // 不包含文件的接口使用application/x-www-form-urlencoded请求头请求
    public static String post(String httpUrl, String bodyParams) {
        return post(httpUrl, null, bodyParams);
    }

    /**
     * 不包含文件的接口使用application/x-www-form-urlencoded请求头请求
     *
     * @param httpUrl
     * @param headerParams
     * @param bodyParams   请求体, 格式: username=张三&password=124&age=22
     * @return
     */
    public static String post(String httpUrl, Map<String, String> headerParams, String bodyParams) {
        BufferedReader reader = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            // 添加请求头
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + StandardCharsets.UTF_8);
            if (headerParams != null && !headerParams.isEmpty()) {
                for (Map.Entry<String, String> kv : headerParams.entrySet()) {
                    httpConn.setRequestProperty(kv.getKey(), kv.getValue());
                }
            }
            //添加请求体
            System.out.println("IOT -->> 请求体 " + bodyParams);
            httpConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
            if (bodyParams != null) {
                writer.write(bodyParams);
            }
            writer.flush();
            writer.close();
            int status = httpConn.getResponseCode();
            InputStream is = null;
            if (status == HttpURLConnection.HTTP_OK) {
                is = httpConn.getInputStream();
            } else {
                is = httpConn.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(is, String.valueOf(StandardCharsets.UTF_8)));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            log.error("http post 通信异常 {}", e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("关闭流异常", e);
                }
            }
        }
        return null;
    }

    /**
     * @param httpUrl
     * @param headerParams
     * @param params
     * @return
     */
    public static String postJson(String httpUrl, Map<String, ?> headerParams, Map<String, ?> params) {
        BufferedReader reader = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            // 添加请求头
            httpConn.setRequestProperty("Content-Type", "application/json; charset=" + StandardCharsets.UTF_8);
            if (headerParams != null && !headerParams.isEmpty()) {
                for (Map.Entry<String, ?> kv : headerParams.entrySet()) {
                    httpConn.setRequestProperty(kv.getKey(), String.valueOf(kv.getValue()));
                }
            }
            //添加请求体
            httpConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
            if (params != null) {
                writer.write(JSON.toJSONString(params));
            }
            writer.flush();
            writer.close();
            int status = httpConn.getResponseCode();
            InputStream is = null;
            if (status == HttpURLConnection.HTTP_OK) {
                is = httpConn.getInputStream();
            } else {
                is = httpConn.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(is, String.valueOf(StandardCharsets.UTF_8)));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            log.error("http通信异常 {}", e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("关闭流异常", e);
                }
            }
        }
        return null;
    }

    // 不包含文件的接口使用application/x-www-form-urlencoded请求头请求
    public static String get(String httpUrl, Map<String, String> headerParams) {
        BufferedReader reader = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            // 添加请求头
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + StandardCharsets.UTF_8);
            if (headerParams != null && !headerParams.isEmpty()) {
                for (Map.Entry<String, String> kv : headerParams.entrySet()) {
                    httpConn.setRequestProperty(kv.getKey(), kv.getValue());
                }
            }
            httpConn.setDoOutput(true);
            int status = httpConn.getResponseCode();
            InputStream is = null;
            if (status == HttpURLConnection.HTTP_OK) {
                is = httpConn.getInputStream();
            } else {
                is = httpConn.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(is, String.valueOf(StandardCharsets.UTF_8)));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            log.error("http通信异常 {}", e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("关闭流", e);
                }
            }
        }
        return null;
    }

    /**
     * Get 请求
     *
     * @param httpUrl 地址
     * @return 响应字节数组
     */
    public static byte[] get(String httpUrl) {
        InputStream is = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setDoOutput(true);
            int status = httpConn.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                is = httpConn.getInputStream();
            } else {
                is = httpConn.getErrorStream();
            }
            return readInputStream(is);
        } catch (IOException e) {
            log.error("http get 通信异常 {}", e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("关闭流", e);
                }
            }
        }
        return null;
    }

    /**
     * 读取 字节流
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    public static void main(String[] args) {
        String url = "https://granwin-agora-certificate.s3.cn-north-1.amazonaws.com.cn/IVFESU2JKNWTQTLMJFEUWU2TFVIUGMBQGAYDAMBQGAYDAMBQGAYDCOI_privateKey?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220921T020641Z&X-Amz-SignedHeaders=host&X-Amz-Expires=900&X-Amz-Credential=AKIA2GSSRHSL2SINOCY6%2F20220921%2Fcn-north-1%2Fs3%2Faws4_request&X-Amz-Signature=ec4605754a5d5a0c503f7c8d000da6c5b76760985f95c73c9bce906dedca76c9";
//        url = "http://10.10.0.10:1014/actuator/health";
        url = "https://granwin-agora-certificate.s3.cn-north-1.amazonaws.com.cn/IVFESU2JKNWTQTLMJFEUWU2TFVIUGMBQGAYDAMBQGAYDAMBQGAYDCOI_privateKey?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220921T033634Z&X-Amz-SignedHeaders=host&X-Amz-Expires=900&X-Amz-Credential=AKIA2GSSRHSL2SINOCY6%2F20220921%2Fcn-north-1%2Fs3%2Faws4_request&X-Amz-Signature=55723f171da32824cedfa418a5c8f616ea9a677f8e366b5fe28179cdf3c6ecf3";
        byte[] bytes = get(url);
        System.out.println(new String(bytes));
    }


}
